/**
 * Created by wangshaohua on 2018/1/25.
 */
moduleContent.controller("AddContentQuiz", function (ExerciseContentResource, UploadFileService, $$CambioConfig, $scope, $log, $state, $stateParams, GeneralResource, LoadingService, ConstantService, DialogService) {
    initPage($scope);
    $scope.$on("ngDialog.opened", function () {
        dialogOnLoad();
        $scope.currentContentQuiz = {
            parentId: $scope.currentParentId,
            picture: LearningMapTemplateUtils.findExercise('EXAMINATION').picture
        };
    });

    // ------------------------------------------------------------------------------------------------------

    $scope.cancel = function () {
        DialogService.close();
    };

    $scope.submit = function () {
        $scope.currentContentQuiz.recordType = Enums.ExerciseContentRecordTypeEnum.CONTENT;
        $scope.currentContentQuiz.studyClassType = Enums.StudyClassTypeEnum.EXAMINATION;
        $scope.currentContentQuiz.space = Enums.ExerciseContentSpaceEnum.QUIZ;
        Alert.confirm(function () {
            ExerciseContentResource.saveQuiz({}, $scope.currentContentQuiz, function (result) {
                $scope.$parent.quizId = result.data.value;
                Alert.success();
                DialogService.close();
            });
        })
    }

    // ------------------------------------------------------------------------------------------------------
    // ------------------------------------------------------------------------------------------------------
    function checkWBJson(rawJson) {
        var first = rawJson[0];
        /** @namespace first.Answer */
        /** @namespace first.Title */
        return (first && first.Title && first.Type && first.A && first.B && first.Answer);
    }

    function addAttribute(answer, itemCode, sort, content, currentTopic) {
        if (StringUtils.isNlOrUndOrEmpty(content)) {
            return;
        }
        var currentAttribute = {};
        currentAttribute.sort = sort;
        currentAttribute.score = answer.includes(itemCode) ? 1 : 0;
        currentAttribute.content = content;
        currentTopic.attributes.push(currentAttribute);
    }

    function jsonToQuizTopicWB(rawJson) {
        var topicList = [];
        rawJson.forEach(function (rawQuizTopic, index) {
            var currentTopic = {};
            currentTopic.itemCode = index + 1;
            if (parseInt(rawQuizTopic['Type']) === 0) {
                currentTopic.type = 'SELECT'
            } else {
                currentTopic.type = 'CHECKBOX_BOOLEAN';
            }
            currentTopic.content = rawQuizTopic['Title'];
            currentTopic.attributes = [];
            addAttribute(rawQuizTopic.Answer, 'A', 1, rawQuizTopic.A, currentTopic);
            addAttribute(rawQuizTopic.Answer, 'B', 2, rawQuizTopic.B, currentTopic);
            addAttribute(rawQuizTopic.Answer, 'C', 3, rawQuizTopic.C, currentTopic);
            addAttribute(rawQuizTopic.Answer, 'D', 4, rawQuizTopic.D, currentTopic);
            addAttribute(rawQuizTopic.Answer, 'E', 5, rawQuizTopic.E, currentTopic);
            addAttribute(rawQuizTopic.Answer, 'F', 6, rawQuizTopic.F, currentTopic);
            topicList.push(currentTopic);
        });
        return topicList;
    }

    /**
     * "[{
     *      "Title":"“倒拿或乱用工具会导致事故”，这种说法正确吗？",
     *      "Type":"0",
     *      "question_knowledge":"正确",
     *      "level":"0",
     *      "Pk":"1",
     *      "Map":"1",
     *      "A":"正确",
     *      "B":"错误",
     *      "Answer":"A"
     *  },{
     *      "Title":"文中，梯子、梯凳有几条安全须知？",
     *      "Type":"0",
     *      "question_knowledge":"9条",
     *      "level":"0",
     *      "Pk":"1",
     *      "Map":
     *      "1",
     *      "A":"9条",
     *      "B":"6条",
     *      "C":"7条",
     *      "D":"8条",
     *      "Answer":"A"
     *  }]"
     * @param workbook
     */
    $scope.readWB = function (workbook) {
        /* DO SOMETHING WITH workbook HERE */
        $log.debug(workbook);
        var rawJson = XLS.utils.sheet_to_json(workbook.Sheets[workbook.SheetNames[0]]);
        $log.debug("excel数据", rawJson);
        if (!checkWBJson(rawJson)) {
            Alert.error(LanguageService.language('数据格式错误!'));
        } else {
            var topicList = jsonToQuizTopicWB(rawJson);
            $log.debug("转换后数据", topicList);
            //$scope.currentQuizTopicGroup.gaugeTopics = topicList;
            $scope.currentContentQuiz.topics = topicList;
            $scope.$apply();
        }
    };

    // ------------------------------------------------------------------------------------------------------
    // ------------------------------------------------------------------------------------------------------
    $scope.uploadPicture = function ($files) {
        if ($files && $files[0]) {
            UploadFileService.uploadFile($files[0], $$CambioConfig.UPLOAD_URL, 'IMG', $scope).then(function (o) {
                $scope.currentContentQuiz.picture = o.id;
            });
        }
    };
});